#include "creatsocket.h"

int creatsock(int prot)
{

    // 申请套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);

    if (-1 == sockfd)
    {
        perror("socket");
        exit(EXIT_FAILURE);
    }
    // printf("sockfd = %d\n", sockfd);

    //  设置属性

    // 设置套接字的SO_REUSADDR 的属性为 1，以开启地址复用
    int val = 1;
    setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
    // setsockopt(send_sock_listen, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));

    struct sockaddr_in saddr = {0};
    // memset(&saddr, '\0', sizeof(saddr));
    saddr.sin_family = AF_INET;         // 通信域
    saddr.sin_addr.s_addr = INADDR_ANY; // IP
    saddr.sin_port = htons(prot);       // 端口

    socklen_t sock_len = 0;
    sock_len = sizeof(saddr);

    if (-1 == bind(sockfd, (struct sockaddr *)&saddr, sizeof(saddr)))
    {
        perror("bind error");
        exit(EXIT_FAILURE);
    }

    if (-1 == listen(sockfd, 100))
    {
        perror("listen error");

        exit(EXIT_FAILURE);
    }

    return sockfd;
}